﻿/**
 * pixSWX is SWXformat API for pixLib
 *  
 * Copyright © 2007 Laurent Deketelaere, Aral Balkan, Francis Bourre
 * Part of the SWX (SWF Data Exchange Format) project. http://swxformat.org
 * Part of the pixLib project. http://pixlib.org
 *
 * Released under the open source MIT license.
 * http://opensource.org/licenses/mit-license.php
 */
import org.triptyk.pixswx.ISWXListener;
import org.triptyk.pixswx.SWXCall;
import org.triptyk.pixswx.SWXMethod;
import org.triptyk.pixswx.SWXResponder;

import com.bourre.events.EventBroadcaster;
import com.bourre.log.PixlibStringifier;
import com.bourre.utils.ClassUtils;

class org.triptyk.pixswx.SWXProxy 
{
	private var _oEB : EventBroadcaster;
	private var _sURL : String;
	private var _sServiceName : String;

	public function SWXProxy( sURL : String, serviceName : String ) 
	{
		_oEB = new EventBroadcaster(this);
		setURL(sURL);
		_sServiceName = serviceName ? serviceName : ClassUtils.getFullyQualifiedClassName(this);
	}

	public function setURL( url : String ) : Void
	{
		_sURL = url;
	}

	public function getURL() : String
	{
		return _sURL;
	}

	/*
	 * event system
	 */
	public function addListener( oL : ISWXListener ) : Void
	{
		_oEB.addListener(oL);
	}

	public function removeListener( oL : ISWXListener ) : Void
	{
		_oEB.removeListener(oL);
	}

	public function addEventListener( e : SWXMethod, oL, f : Function ) : Void
	{
		_oEB.addEventListener.apply(_oEB, arguments);
	}

	public function removeEventListener( e : SWXMethod, oL ) : Void
	{
		_oEB.removeEventListener(e, oL);
	}

	public function callMethod( oServiceMethodName : SWXMethod, swxlistener : ISWXListener ) : Void
	{
		arguments.splice(0, 2);
		
		var sFullyQualifiedMethodName : String = _sServiceName + "." + oServiceMethodName;
		var swxCall : SWXCall = new SWXCall(getURL(), sFullyQualifiedMethodName);

		if(swxlistener) 
		{
			swxCall.addListener(swxlistener);
			if(swxlistener instanceof SWXResponder) SWXResponder(swxlistener).setMethodName(sFullyQualifiedMethodName);
		}
		swxCall.load.apply(swxCall, arguments);
	}

	public function toString() : String 
	{
		return PixlibStringifier.stringify(this);
	}	
}